package main

import (
	"echo-utils/global"
	"echo-utils/internal/dao"
	"echo-utils/internal/routers"
	"echo-utils/internal/service"
	"echo-utils/pkg/logger"
	"log"
	"net/http"
	"os"
	"time"

	"echo-utils/pkg/setting"

	"gopkg.in/natefinch/lumberjack.v2"
	"xorm.io/xorm"
)

func main() {
	router := routers.NewRouter()
	s := &http.Server{
		Addr:           ":" + global.ServerSetting.HttpPort,
		Handler:        router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}

func init() {
	errS := setupSetting()
	if errS != nil {
		log.Fatalf("init.setupSetting err : %v", errS)
	}

	errL := setupLogger()
	if errL != nil {
		log.Fatalf("init.setupLogger err : %v", errL)
	}

	errD := setupDBEngine()
	if errD != nil {
		log.Fatalf("init.setupDBEngine err : %v", errD)
	}

	errSDB := syncDB()
	if errSDB != nil {
		log.Fatalf("init.syncDB err : %v", errSDB)
	}

	clearLogs()
	global.Logger.Info("初始化完成")
}

func setupLogger() error {
	global.Logger = logger.NewLogger(&lumberjack.Logger{
		Filename:  global.ProDirectory + "/storage/logs.txt",
		MaxSize:   600,
		MaxAge:    10,
		LocalTime: true,
	}, "", log.LstdFlags).WithCaller(2)
	return nil
}

func setupSetting() error {
	directory, err := os.Getwd()
	if err != nil {
		return err
	}
	global.ProDirectory = directory

	setting, err := setting.NewSetting()
	if err != nil {
		return err
	}
	err = setting.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}

	return nil
}

func setupDBEngine() error {
	engine, err := xorm.NewEngine("sqlite3", global.ProDirectory+"/storage/echo.db")
	if err != nil {
		return err
	}
	engine.ShowSQL(false)
	global.DBEngine = engine
	return nil
}

func syncDB() error {
	db := service.NewDB(global.DBEngine)
	return db.Sync()
}

func clearLogs() {
	os.Truncate(global.ProDirectory+"/storage/logs.txt", 0)
	idao := dao.NewIlogDao()
	idao.Clear()
}
